
import http from "../../utils/http_promise.js";
import WxValidate from '../../utils/WxValidate.js';

let app = getApp();
let baseUrl = app.globalData.baseUrl;

// pages/house/create.js

Page({

  /**
   * 页面的初始数据
   */
  data: {
     imgArr:[],
     imgs:[],
     index:0,
     form:{
        title:"",
        des:"",
        tel:""
     },
     header:{}
  },

  del(e){

    //console.log(e.currentTarget.dataset.index);
    let index = e.currentTarget.dataset.index;
    let tmpArr = this.data.imgArr;
    tmpArr.splice(index,1);

    this.setData({
      imgArr: tmpArr
    })
    
  },

  initValidate() {

    // 验证规则
    const rules = {
      title: {
        required: true,
        minlength: 5,
        maxlength: 25
      },
      des: {
        required: true,
        minlength: 5,
        maxlength: 300
      },
      tel: {
        required: true,
        tel: true
      }
    }
    
    // 提示信息
    const messages = {
      title: {
        required: "请输入房源标题!",
        minlength:"房源标题至少5位",
        maxlength:"房源标题不多于25位"
      },
      des: {
        required: "请输入房源详情!",
        minlength: "房源详情至少5位",
        maxlength: "房源详情不超过300位"
      },
      tel: {
        required: "请输入手机号码!",
        tel: "请输入正确手机号码"
      }
    }

    // 自定义验证规则
    this.WxValidate = new WxValidate(rules, messages);
  
  },
  
  chooseImage(){

    let that = this;

    // 选择图片api接口 
    wx.chooseImage({
      count: 3,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        
        let tmpArr = [];
        tmpArr = that.data.imgArr.concat(res.tempFilePaths);

         that.setData({
            imgArr:tmpArr
         })

      }
    })


  },
 
  
  onSubmit(e){

    let that = this;

    // 验证是否登录
    http.checkLogin();

    // 图片验证
    if(that.data.imgArr.length == 0){
       wx.showModal({
         title: '提示信息',
         content: '亲,至少选择一张图片'
       })
       return false;
    }
    
    // 表单验证
    let params = e.detail.value;
    that.data.formData = e.detail.value; 

    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0];
      wx.showModal({
        title: '提示信息',
        content:error.msg
      });
      return false
    }

    // 设置token
    let token = wx.getStorageSync("token");
    that.data.header.Authorization = 'Bearer ' + token;

    // 上传文件
    that.uploadFile(that.data.imgArr[that.data.index]); 
    
  },

  uploadFile(picPath){
    
    let that = this;
    // 2 上传文件;
    wx.uploadFile({

      url: baseUrl + "/house/upload",
      filePath: picPath,
      name: 'file',
      header:that.data.header,
      formData: {
        'index': that.data.index
      },

      success(res) {
        that.data.imgs.push(res.data);
        that.data.index++;
        if(that.data.index<that.data.imgArr.length){
          that.uploadFile(that.data.imgArr[that.data.index]);
        }else{
            //处理图片全部上传完成的业务逻辑
            console.log("success");
            Object.assign(that.data.formData,{'imgs':that.data.imgs});
            that.save();
        }
        
        
      }
    
    })
    
  },
  
  save(){

     // 3 保存表单数据
     let that = this;
     
     http.request({
        url:"/house/save",
        data:that.data.formData,
        requireAuth:true,
        method:"post",
        header:that.data.header
     })
     
     .then(res=>{
        
        if(res.data.status == "201"){
          wx.showToast({
            title: res.data.msg,
          })
          setTimeout(()=>{
             wx.navigateTo({
               url: '/pages/house/my_houses'
             })
          },2000)
        }
        
     })
     
     
  },

  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    http.checkLogin();
    this.initValidate();
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
     
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
  

})